package com.example.auth.interceptor;

import com.example.auth.exception.LyException;
import com.example.auth.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: LiYang
 * @create: 2023-07-28 10:00
 * @Description:
 * @Version 1.0
 **/
@Component
public class RequestInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        判断请求头中是否有token
        var token = request.getHeader("Access-Token");
        //判断redis中token是否过期
        var sysUser = redisUtil.get(token);
        if(ObjectUtils.isEmpty(sysUser)){
            throw new LyException(50014,"token过期了");
        }
        if(redisUtil.getExpire(token) < 10 * 60){
            redisUtil.expire(token,30*60);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
